<template>
  <view :class="theme">
    <view class="relative overflow-hidden">
      <swiper :autoplay="true" circular @change="changeBanner" style="height: 680rpx;">
        <swiper-item v-for="(banner, index) in goodsInfo.goods_img_banner || []" :key="index">
          <uv-image @click="uniPreviewImage({ urls: goodsInfo.goods_img_banner || [], current: index })"
            class="w-full h-full" width="100%" height="100%" :src="include(banner)" />
        </swiper-item>
      </swiper>
      <label class="justify-center absolute bottom-30 right-40 text-28 color-base b-rounded-24"
        style="background-color: rgba(0,0,0,0.3); padding: 4rpx 22rpx;">
        {{ bannerCurrent + 1 }}/{{ goodsInfo.goods_img_banner?.length || 0 }}
      </label>
    </view>

    <view class="bg-section b-rounded-10 m-30 p-30">
      <text class="multi-ellipsis text-28">{{ goodsInfo.goods_name || "-" }}</text>
      <view class="mt-20 flex-row items-center justify-between">
        <label class="items-baseline flex-wrap">
          <text class="color-stress">
            <text class="text-60 fw-700">{{ Number(goodsInfo.price || 0).toFixed(2) }}</text>
          </text>
          <text v-if="goodsInfo.max_price" class="ml-16 color-placeholder text-28" style="text-decoration: line-through;">
            {{ goodsInfo.max_price }}
          </text>
        </label>
        <text class="color-placeholder">已售{{ goodsInfo.sales_volume || 0 }}件</text>
      </view>
    </view>

    <view class="bg-section b-rounded-10 ml-30 mr-30">
      <label @click="changePopup(true, 'spec')" class="ml-30 mr-30 pt-30 pb-30"
        style="border-bottom: 2rpx solid rgba(151,151,151,0.1);">
        <text>规格</text>
        <text class="flex-1 ml-70 mr-30">请选择规格/购买数量</text>
        <uv-icon size="20" color="#666" name="arrow-right" />
      </label>
      <label class="p-30">
        <text>说明</text>
        <text class="flex-1 ml-70 mr-30 multi-ellipsis">全国包邮，偏远地区除外</text>
      </label>
    </view>

    <label class="m-30 items-baseline">
      <text class="text-32 fw-600">产品详情</text>
      <text class="ml-6">Product Details</text>
    </label>

    <view class="overflow-hidden lh-[2]" style="margin: 0 30rpx calc(150rpx + env(safe-area-inset-bottom));">
      <uv-parse :content="goodsInfo.goods_remark" :domain="$config.URL_ASSETS" />
      <!-- <uv-image v-for="src in goodsInfo.des_images" :key="src" width="100%" :src="include(src" mode="widthFix)" /> -->
    </view>

    <view class="fixed content-box safe-area-inset-bottom bottom-0 flex-row h-100"
      style="left: var(--window-left); right: var(--window-right); background-color: rgba(255, 255, 255, 0.9); backdrop-filter: blur(24rpx);">
      <!-- <button
        @click="uniCopyText({ data: `【${$config.APP_NAME}】「${goodsInfo.goods_name}」1-${goodsInfo.goods_sn} 复制内容打开APP查看`, showToast: true })"
        open-type="share" class="flex-1 items-center justify-center b-rounded-0 lh-1" plain
        style="padding: 0; border: 2rpx solid rgba(151,151,151,0.1); border-width: 0 2rpx 0 0; background-color: rgba(11, 1, 38, 0.6);">
        <uv-icon name="share" size="54" :color="$config.COLOR_WHITE" />
        <text class="text-22 color-base mt-16">分享</text>
      </button> -->

      <!-- <view @click="uniNavigator({ url: '/pages/client/mall/cart' })" class="flex-1 items-center justify-center lh-1">
        <uv-icon name="shopping-cart" size="54" :color="$config.COLOR_SUBTITLE" />
        <text class="text-22 mt-12 color-subtitle">购物车</text>
      </view> -->

      <view class="flex-grow-3 flex-basis-none flex-row text-30 color-base">
        <!-- <view @click="buy('joinCart')" hover-class="op-[0.6]" hover-stay-time="50"
          class="flex-1 bg-9 items-center justify-center">
          <text>加入购物车</text>
        </view> -->
        <view @click="buy('buy')" hover-class="op-[0.6]" hover-stay-time="50"
          class="flex-1 bg-primary color-base items-center justify-center fw-bold">
          <text>立即购买</text>
        </view>
      </view>
    </view>

    <uv-popup :ref="(e: AnyObject) => (showPopup.spec = e)" mode="bottom" closeable
      :close-icon-color="$config.COLOR_DISABLED" round="30">
      <view class="bg-base" style="padding: 60rpx 30rpx 30rpx;">
        <view class="flex-row items-center">
          <uv-image @click="uniPreviewImage({ urls: [goodsSpecs.picture || goodsInfo.goods_img] })" radius="6" width="200"
            height="200" :src="include(goodsSpecs.picture || goodsInfo.goods_img)" mode="aspectFit)" />
          <view class="ml-30 ai-start">
            <text class="text-28">{{ goodsInfo.goods_name || "-" }}</text>
            <label class="mt-10 items-baseline">
              <text class="text-40 color-stress fw-700">{{ Number(goodsSpecs.price || 0).toFixed(2) }}</text>
              <text v-if="goodsSpecs.original_price" class="ml-16 color-placeholder text-28"
                style="text-decoration: line-through;">
                {{ Number(goodsSpecs.original_price || 0).toFixed(2) }}
              </text>
            </label>
          </view>
        </view>

        <scroll-view scroll-y
          style="margin: 30rpx 0 0; max-height: 50vh; border-bottom: 2rpx solid rgba(151,151,151,0.1);">
          <view class="mt-30 mb-30 flex-row flex-wrap">
            <label @click="buyFormData.specIndex = index;" v-for="(item, index) in goodsInfo.goods_spec" :key="index"
              :class="[buyFormData.specIndex === index ? 'color-base bg-primary' : 'color-placeholder bg-0', 'b-rounded-28 m-16']"
              :style="{ border: `1px solid ${buyFormData.specIndex === index ? '#8777e1' : '#7f7f7f'}`, padding: `8rpx 30rpx` }">
              {{ item.spec_text || "-" }}
            </label>
          </view>
        </scroll-view>

        <view class="mt-30 flex-row items-center">
          <text class="text-28">购买数量</text>
          <text class="ml-40 mr-30 flex-1 color-placeholder">剩余库存 {{ goodsSpecs.stock || 0 }}</text>
          <uv-number-box v-model="buyFormData.number" @change="changeBuyNumber" input-width="70" integer
            :max="goodsSpecs.stock || 1" />
        </view>

        <button @click="confirmSubmit" hover-class="op-[0.6]" style="margin: 80rpx 0 0; line-height: 88rpx;"
          class="bg-primary b-rounded-16 text-36 color-base">
          确认
        </button>
      </view>
    </uv-popup>
  </view>
</template>

<script lang="ts" setup>
import { useMapState } from "@/common/libs/store";
import { uniCopyText, uniNavigator, uniPreviewImage } from "@/common/libs/utils";
import { onLoad, onNavigationBarButtonTap } from "@dcloudio/uni-app";
import { ref, reactive, computed } from "vue";
import { useStore } from "vuex";

const { $config = {} } = getApp().globalData || {};
const { theme, shoppingCart } = useMapState(["theme", "shoppingCart"]);
const store = useStore();
const goodsInfo = reactive<AnyObject>({});
const buyFormData = reactive({
  number: 1,
  specIndex: 0
});
const showPopup = reactive({
  spec: {} as AnyObject,
});
const bannerCurrent = ref(0);

const changeBanner = ({ detail }: any) => {
  bannerCurrent.value = detail.current;
}

const goodsSpecs = computed(() => goodsInfo.goods_spec?.[buyFormData.specIndex] || {});

const changePopup = (e: boolean, popupKey: keyof typeof showPopup) => {
  showPopup[popupKey][e ? "open" : "close"]();
};

onNavigationBarButtonTap(() => {
  uniCopyText({ data: `【${$config.APP_NAME}】「${goodsInfo.goods_name}」1-${goodsInfo.goods_sn} 复制内容打开APP查看`, showToast: true });
});

onLoad(({ sn }: any) => {
  uni.pageScrollTo({
    scrollTop: 0
  });
  uni.request({
    url: "/goodsDetails",
    data: { goods_sn: sn },
    success({ data }: any) {
      Object.assign(goodsInfo, data);
      uni.setNavigationBarTitle({ title: data.goods_name });
    }
  })
});
let type: "joinCart" | "buy" = "buy";
const buy = (params: "joinCart" | "buy") => {
  type = params;
  changePopup(true, "spec");
}

const confirmSubmit = () => {
  const data = {
    goods_sn: goodsInfo.goods_sn,
    spec_id: goodsSpecs.value.spec_ids,
    num: buyFormData.number
  };

  if (!goodsSpecs.value.stock) {
    return uni.showToast({ title: "库存不足", icon: "error" });
  }
  if (type === "joinCart") {
    if (shoppingCart.value.length > 30) {
      uni.showModal({
        title: "加入购物车失败",
        content: "购物车最多只能加入30件商品~",
        showCancel: false
      });
      return;
    }

    const goodsInCartIndex = shoppingCart.value.findIndex((item: any, index: number) =>
      (item.goods_sn === data.goods_sn && item.goods_spec_id === data.spec_id));

    if (goodsInCartIndex < 0) {
      store.commit("setState", { key: "shoppingCart", value: [...shoppingCart.value, data] });
    } else {
      shoppingCart.value[goodsInCartIndex].num += data.num;
      store.commit("setState", { key: "shoppingCart", value: [...shoppingCart.value] });
    }
    uni.showToast({ title: "已加入购物车！" });
  }

  if (type === "buy") {
    store.commit("setState", {
      key: "confirmOrder", value: [data]
    });
    uniNavigator({ url: `/pages/client/mall/confirmOrder` });
  }

  changePopup(false, "spec")
}

const changeBuyNumber = (e: any) => {
  buyFormData.number = e.value;
}

</script>

<style lang="scss" scoped>
// scss

::v-deep {
  .rich-text {
    font-size: 30rpx;
    line-height: 2;

    img {
      max-width: 100% !important;
      height: auto !important;
    }
  }
}
</style>